/*
 * Toedo
 * Copyright (C) 2009-2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package org.toedo.model.comparators;

import java.util.Comparator;
import java.util.Date;

import org.toedo.controllers.Controller;
import org.toedo.model.Task;
import org.toedo.model.enums.SortDirection;
import org.toedo.model.enums.TaskField;
import org.toedo.preferences.PreferenceConstants;

public class TaskComparator implements Comparator<Task> {
	
	private TaskField mCompareField;
	private SortDirection mSortDirection;
	
	public TaskComparator() {
		mCompareField = TaskField.getValueOf(Controller.getInstance().getPreferenceStore().getString(PreferenceConstants.TASKSLIST_SORT_FIELD));
		mSortDirection = SortDirection.getValueOf(Controller.getInstance().getPreferenceStore().getString(PreferenceConstants.TASKSLIST_SORT_DIRECTION));
	}
	
	private int getIntResult(int arg0, int arg1) {
		switch(mSortDirection) {
		case EnAscending : return Integer.valueOf(arg0).compareTo(Integer.valueOf(arg1));
		case EnDescending : return Integer.valueOf(arg1).compareTo(Integer.valueOf(arg0));
		default : return Integer.valueOf(arg0).compareTo(Integer.valueOf(arg1));
		}
	}
	
	private int getStringResult(String arg0, String arg1) {
		switch(mSortDirection) {
		case EnAscending : return arg0.compareToIgnoreCase(arg1);
		case EnDescending : return arg1.compareToIgnoreCase(arg0);
		default : return arg0.compareToIgnoreCase(arg1);
		}
	}
	
	private int getDateResult(Date arg0, Date arg1) {
		switch(mSortDirection) {
		case EnAscending : return arg0.compareTo(arg1);
		case EnDescending : return arg1.compareTo(arg0);
		default : return arg0.compareTo(arg1);
		}
	}
	
	@Override
	public int compare(Task arg0, Task arg1) {
		switch(mCompareField) {
		case EnPriority : return getIntResult(arg0.getPriority(), arg1.getPriority());
		case EnTitle : return getStringResult(arg0.getTitle(), arg1.getTitle());
		case EnStartDate : return getDateResult(arg0.getStartDate(), arg1.getStartDate());
		case EnDueDate : return getDateResult(arg0.getDueDate(), arg1.getDueDate());
		case EnDaysLeft : return getIntResult(arg0.getDeltaInDays(), arg1.getDeltaInDays());
		default : return getStringResult(arg0.getTitle(), arg1.getTitle());
		}
	}

}
